package com.maxbill.fxui.left;

import com.maxbill.base.bean.Connect;
import com.maxbill.base.bean.TreeBean;
import com.maxbill.base.service.ConnectService;
import javafx.scene.control.TreeItem;
import javafx.scene.control.TreeView;
import javafx.scene.input.MouseButton;

import java.util.ArrayList;
import java.util.List;

import static com.maxbill.fxui.util.CommonConstant.STYLE_LEFT;
import static com.maxbill.fxui.util.CommonConstant.STYLE_SCROLL;
import static com.maxbill.fxui.util.DesktopObjects.context;

/**
 * 左部窗口
 *
 * @author MaxBill
 * @date 2019/07/06
 */
public class LeftWindow {

    public static TreeView getLeftWindow() {
        List<TreeItem<TreeBean>> treeItems = new ArrayList<>();
        List<Connect> dataList = context.getBean(ConnectService.class).selectConnectList();
        if (null != dataList && !dataList.isEmpty()) {
            for (Connect connect : dataList) {
                TreeItem<TreeBean> treeItem = new TreeItem<>(new TreeBean(connect));
                treeItem.setExpanded(false);
                treeItems.add(treeItem);
            }
        }

        TreeItem<TreeBean> treeRoot = new TreeItem<>();
        treeRoot.getChildren().addAll(treeItems);

        TreeView<TreeBean> leftWindow = new TreeView<>(treeRoot);
        leftWindow.setShowRoot(false);
        leftWindow.setPrefWidth(250);
        leftWindow.setId("left-pane");
        leftWindow.getStylesheets().add(STYLE_LEFT);
        leftWindow.getStylesheets().add(STYLE_SCROLL);

        leftWindow.setOnMouseClicked(event -> {
            TreeItem<TreeBean> currTreeItem = leftWindow.getSelectionModel().getSelectedItem();
            // 双击事件
            if (event.getClickCount() == 2) {
                boolean expandFlag = currTreeItem.isExpanded();
                if (expandFlag) {
                    currTreeItem.setExpanded(false);
                    currTreeItem.getChildren().clear();
                } else {
                    currTreeItem.setExpanded(true);
                    currTreeItem.getChildren().addAll(getDataList());
                }
            }
            //右击事件
            if (event.getButton() == MouseButton.SECONDARY) {
                System.out.println("123");
            }
        });

        return leftWindow;
    }

    private static TreeView<Connect> showTreeListBack(List<TreeItem<Connect>> treeItems) {
        TreeItem<Connect> treeRoot = new TreeItem<>();
        treeRoot.getChildren().addAll(treeItems);
        TreeView<Connect> treeView = new TreeView<>(treeRoot);
        treeView.setShowRoot(false);
        return treeView;
    }

    private static List<TreeItem<TreeBean>> getDataList() {
        List<TreeItem<TreeBean>> dataList = new ArrayList<>();
        for (int i = 0; i < 15; i++) {
            TreeItem<TreeBean> item = new TreeItem<>(new TreeBean("" + i, "db(" + i + ")"));
            dataList.add(item);
        }
        return dataList;
    }

}
